/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */

package cn.com.ksplatform.common.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:BaseDaoUtil <br/>
 * Date: 2015年5月20日 上午9:43:21 <br/>
 * 
 * @author Mr.Luoxing
 * @version 1.0
 */

public class BaseDaoUtil {
	
	/**
	 * 
	 * getPKName:获取基于注解实体类主键. <br/>
	 * 
	 * @author Mr.Luoxing
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static String getPKName(Class clazz) {
		Field[] fields = clazz.getDeclaredFields();
		for (Field f : fields) {
			Annotation[] annotations = f.getAnnotations();
			if (annotations.length <= 0) {
				String name = f.getName();
				String setMethodName = "get" + org.apache.commons.lang.StringUtils.left(name, 1).toUpperCase() + org.apache.commons.lang.StringUtils.substring(name, 1);
				try {
					Method method = clazz.getDeclaredMethod(setMethodName);
					annotations = method.getAnnotations();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			for (Annotation anno : annotations) {
				if (anno.toString().contains("@javax.persistence.Id()"))
					return f.getName();
			}
		}
		return null;
	}
	
	/**
	 * 获取类映射
	 * @param clazz
	 * @return
	 */
	public static Map<String, Class> getRowMapper(Class clazz) {
		Map<String, Class> map = new HashMap<String, Class>();
		Field[] fields = clazz.getDeclaredFields();
		for(Field field: fields){
			map.put(field.getName(), field.getType());
		}
		return map;
	}
}
